package com.wan.controller;

import com.wan.pojo.Authority;
import com.wan.pojo.Menu;
import com.wan.pojo.Role;
import com.wan.pojo.User;
import com.wan.service.*;
import com.wan.utils.CpachaUtil;
import com.wan.utils.MenuUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
系统操作类控制器
* */
@Controller
@RequestMapping("/system")
public class SystemController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private LogService logService;
    /*
    登录页面
    * */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView login(ModelAndView model){
        model.setViewName("system/login");
        return model;
    }
    /*
  登录成功后的主页
  * */
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public ModelAndView index(ModelAndView model,HttpServletRequest request){
        List<Menu> menuList = (List<Menu>) request.getSession().getAttribute("userMenus");
        model.addObject("topMenuList",MenuUtil.getAllTopMenu(menuList));
        model.addObject("secondMenuList",MenuUtil.getAllSecondMenu(menuList));
        model.setViewName("system/index");
        return model;
    }
    /*
  登录成功后的欢迎页
    * */
    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public ModelAndView welcome(ModelAndView model){
        model.setViewName("system/welcome");
        return model;
    }

    /*
    所有验证码均采用此方法
    CpachaType：用来区分验证码类型（登录页面验证码、注册页面验证码。。。。）
    * */
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public void generateCpacha(
            @RequestParam(name = "vcodeLen",required = false,defaultValue ="4") Integer vcodeLen,
            @RequestParam(name = "width",required = false,defaultValue ="100") Integer width,
            @RequestParam(name = "height",required = false,defaultValue ="30") Integer height,
            @RequestParam(name = "type",required = true,defaultValue ="loginCpacha") String CpachaType,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        CpachaUtil cpachaUtil = new CpachaUtil(vcodeLen,width, height);
        String vCode = cpachaUtil.generatorVCode();
        request.getSession().setAttribute(CpachaType,vCode);
        BufferedImage bufferedImage = cpachaUtil.generatorRotateVCodeImage(vCode, true);
        try {
            ImageIO.write(bufferedImage,"gif",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> loginAct(User user,String cpacha,HttpServletRequest request){
        HashMap<String, String> map = new HashMap<String, String>();
        if(user==null){
            map.put("type","error");
            map.put("msg","请填写用户信息！");
            return map;
        }
        if(StringUtils.isEmpty(user.getUsername())){
            map.put("type","error");
            map.put("msg","请填写用户名！");
            return map;
        }
        if(StringUtils.isEmpty(user.getPassword())){
            map.put("type","error");
            map.put("msg","请填写密码！");
            return map;
        }
        if(StringUtils.isEmpty(cpacha)){
            map.put("type","error");
            map.put("msg","请填写验证码！");
            return map;
        }
        Object loginCpacha = request.getSession().getAttribute("loginCpacha");
        if (loginCpacha == null) {
            map.put("type","error");
            map.put("msg","会话超时，请刷新页面！");
            return map;
        }
        if(!cpacha.toUpperCase().equals(loginCpacha.toString().toUpperCase())){
            map.put("type","error");
            map.put("msg","验证码错误！");
            return map;
        }
        User user1 = userService.findUserByName(user.getUsername());
        if(user1==null){
            map.put("type","error");
            map.put("msg","用户名不存在！");
            return map;
        }
        if(!user.getPassword().equals(user1.getPassword())){
            map.put("type","error");
            map.put("msg","密码错误！");
            return map;
        }
        //说明用户名密码及验证码都正确
        //此时需要查询用户的角色权限
        Role role = roleService.findById(user1.getRoleId());
        List<Authority> authorityList = authorityService.findListByRoleId(role.getId());//根据角色获取权限列表
        String menuIds = "";
        for(Authority authority:authorityList){
            menuIds += authority.getMenuId() + ",";
        }
        if(!StringUtils.isEmpty(menuIds)){
            menuIds = menuIds.substring(0,menuIds.length()-1);
        }
        List<Menu> userMenus = menuService.findListByIds(menuIds);
        //把角色信息、菜单信息放到session中
        request.getSession().setAttribute("admin",user1);
        request.getSession().setAttribute("role",role);
        request.getSession().setAttribute("userMenus", userMenus);

        map.put("type","success");
        map.put("msg","登录成功！");
        logService.add("用户名为{"+user.getUsername()+"}，角色为{"+role.getName()+"}的用户登录成功!");
        return map;
    }
    /**
     * 后台退出注销功能
     * @param request
     * @return
     */
    @RequestMapping(value="/logout",method=RequestMethod.GET)
    public String logout(HttpServletRequest request){

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("admin");
        session.setAttribute("admin", null);
        session.setAttribute("role", null);
        request.getSession().setAttribute("userMenus", null);
        logService.add("用户名为{"+user.getUsername()+"}的用户注销登录!");
        return "redirect:login";
    }
}
